package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种异常（地址簿为空，购物车数据为空）
        //判断地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出地址为空异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //判断购物车是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            //抛出购物车为空的异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        orderMapper.insert(order);

        //向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);

        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //构建返回对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo);
        String json = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(json);
    }

    /**
     * 客户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        //根据id查询订单
        Orders orders = getOrder(id, new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND));

        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        String json = JSON.toJSONString(map);

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //List<OrderVO> orderVOList = new ArrayList<>();
        List<OrderPageQueryVO> orderPageQueryVOList = new ArrayList<>();



        //设置分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        //对订单表进行分页查询
        Page<Orders> page =  orderMapper.PageQuery(ordersPageQueryDTO);
        List<Orders> result = page.getResult();

        for (Orders orders : result) {
            //根据userID查找订单细节表内容
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(BaseContext.getCurrentId());
//            OrderVO orderVO = new OrderVO();
            OrderPageQueryVO orderPageQueryVO = new OrderPageQueryVO();

            BeanUtils.copyProperties(orders,orderPageQueryVO);
            orderPageQueryVO.setOrderDetailList(orderDetails);
            orderPageQueryVOList.add(orderPageQueryVO);
        }

        return new PageResult(page.getTotal(),orderPageQueryVOList);
    }


    /**
     * C端通过具体id查询订单
     * @param id
     * @return
     */
    public OrderVO getById(Long id) {

        OrderVO orderVO = new OrderVO();
        Orders order = orderMapper.getById(id);
        BeanUtils.copyProperties(order,orderVO);

        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * C端取消订单
     * @param id
     */
    public void cancelById(Long id) {
        //通过查询数据库的订单表看看是否有这个订单
        Orders order = getOrder(id, new RuntimeException(MessageConstant.ORDER_STATUS_ERROR));

        //查询到有这个订单号，开始取消相关问题
        //设置订单的相关状态
        order.setStatus(6);
        //该下面应该有退款相关代码关联微信官方的

        order.setPayStatus(2);
        String msg = "用户取消";
        order.setCancelReason(msg);
        order.setCancelTime(LocalDateTime.now());
        //向数据表更新数据
        orderMapper.update(order);
    }



    /**
     * C端再来一单
     * @param id
     */
    @Transactional
    public void repOrder(Long id) {
        //通过查询数据库的订单表看看是否有这个订单
        Orders order1 = getOrder(id, new RuntimeException(MessageConstant.ORDER_STATUS_ERROR));

        Orders order2 = new Orders();
        BeanUtils.copyProperties(order1, order2);
        order2.setId(null);
        order2.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        order2.setNumber(String.valueOf(System.currentTimeMillis()));
        order2.setStatus(Orders.PENDING_PAYMENT);
        order2.setPayStatus(Orders.UN_PAID);
        order2.setOrderTime(LocalDateTime.now());
        order2.setCheckoutTime(null);
        order2.setCancelReason(null);
        order2.setCancelTime(null);
        order2.setRejectionReason(null);
        order2.setDeliveryTime(null);

        orderMapper.insert(order2);

        Long id2 = order2.getId();

        //插入订单关系表
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        for (OrderDetail orderDetail : list) {
            orderDetail.setOrderId(id2);
        }
        orderDetailMapper.insertBatch(list);
    }


    /**
     * 管理端分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult adminPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.adminPage(ordersPageQueryDTO);
        List<Orders> ordersList = orders.getResult();
        List<OrderVO> orderVOLists = new ArrayList<>();
        for (Orders orders1 : ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders1,orderVO);
            orderVOLists.add(orderVO);
        }
        for (OrderVO orderVOList : orderVOLists) {
            Long orderId = orderVOList.getId();
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(orderId);
            String orderDishes = "[";
            for (OrderDetail orderDetail : detailList) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                orderDishes += name + "*" + number + " ,";
            }
            orderDishes += "]";
            orderVOList.setOrderDishes(orderDishes);
        }
        return new PageResult(orders.getTotal(),ordersList);
    }

    /**
     * 管理端查询订单详情
     * @param id
     * @return
     */
    public OrderVO getODById(Long id) {
        //判断传过来的id是否可以查出order
        Orders order = getOrder(id, new RuntimeException(MessageConstant.ORDER_NOT_FOUND));
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);

        //根据查关系表
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(detailList);
        return orderVO;
    }

    /**
     * 管理端接单
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = new Orders();
        order.setId(ordersConfirmDTO.getId());
        //设置接单后的订单相关数据
        order.setStatus(3);
        order.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orderMapper.update(order);
    }

    /**
     * 管理端拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = new Orders();
        order.setId(ordersRejectionDTO.getId());
        //设置接单后的订单相关数据
        order.setStatus(6);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(order);
    }

    /**
     * 管理端派送订单
     * @param id
     */
    public void delivery(Long id) {
        Orders order = new Orders();
        order.setId(id);
        //设置接单后的订单相关数据
        order.setStatus(4);
        orderMapper.update(order);
    }

    /**
     * 管理端完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders order = new Orders();
        order.setId(id);
        //设置接单后的订单相关数据
        order.setStatus(5);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders order = new Orders();
        order.setId(ordersCancelDTO.getId());
        //设置接单后的订单相关数据
        order.setStatus(6);
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(order);
    }

    /**
     * 管理端各个状态的订单数量统计
     * @return
     */
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
//        待接单
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectCount(2));
//        待派送
        orderStatisticsVO.setConfirmed(orderMapper.selectCount(3));
//        派送中
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectCount(4));
        return orderStatisticsVO;
    }

    //通过id查找order
    private Orders getOrder(Long id, RuntimeException ORDER_NOT_FOUND) {
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw ORDER_NOT_FOUND;
        }
        return order;
    }
}
